package com.example.smartcity_ikun_new2.ui.NewsShow

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_ikun_new2.AppContext
import com.example.smartcity_ikun_new2.R
import com.example.smartcity_ikun_new2.databinding.ActivityEditTextShowBinding
import com.example.smartcity_ikun_new2.logic.network.SmartCityNetWorkCreate.Companion.baseUrl
import com.example.smartcity_ikun_new2.ui.home.NewsFragment.NewsViewModel
import com.example.smartcity_ikun_new2.ui.home.adapter.NewsListViewAdapter
import com.example.smartcity_ikun_new2.ui.home.model.NewsEntity

class EditTextShowActivity : AppCompatActivity() {

    private val viewModel by lazy {
        ViewModelProviders.of(this).get(NewsViewModel::class.java)
    }

    private lateinit var mBinding: ActivityEditTextShowBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityEditTextShowBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        title = "搜索结果"

        val EditText = intent.getStringExtra("EditText")

        // 实现模糊查询
        if (EditText != null) setEditTextSeek(EditText.toString())
    }

    private fun setEditTextSeek(ed: String) {
        val arrayAdapter = ArrayList<NewsEntity>()

        mBinding.NewsList.apply {
            this.layoutManager = LinearLayoutManager(context)
            this.adapter = NewsListViewAdapter(arrayAdapter)
        }


        viewModel.setNewsType(null)
        viewModel.newsListLiveData.observe(this, Observer {
            arrayAdapter.clear()
            viewModel.newsList.clear()
            viewModel.newsList.addAll(it.rows)

            for (i in viewModel.newsList){
                ed.forEach { ed ->
                    i.title.forEach {
                        if (ed == it){
                            arrayAdapter.add(
                                NewsEntity(
                                    baseUrl + i.cover,
                                    i.title,
                                    i.content,
                                    i.publishDate,
                                    i.commentNum.toString() + "评论"
                                )
                            )
                            mBinding.NewsList.adapter?.notifyItemInserted(arrayAdapter.size)
                        }
                    }
                }

            }
        })
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}